package com.bestom.hardwaretest.util;

import android.content.Context;
import android.content.SharedPreferences;

import com.bestom.hardwaretest.File.FilesConstant;

import java.util.HashSet;
import java.util.Set;

import static android.content.Context.MODE_PRIVATE;

public class SharedPreferencesUtil {

    private static SharedPreferences SETTING_PREF;

    /**
     * 初始化
     */
    public static void init(Context context) {
        SETTING_PREF = context.getSharedPreferences(FilesConstant.SETTING_PREF, MODE_PRIVATE);
    }
    private static volatile SharedPreferencesUtil instance;

    public static SharedPreferencesUtil getInstance(){
        synchronized (SharedPreferencesUtil.class){
            if (instance==null){
                instance=new SharedPreferencesUtil();
            }
        }
        return instance;
    }

    public void putValue(String key, Object value) {
        SharedPreferences.Editor editor = SETTING_PREF.edit();
        if (value instanceof String) {
            editor.putString(key, (String) value);
        } else if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (Float) value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (Integer) value);
        } else  if (value instanceof Long) {
            editor.putLong(key, (Long) value);
        } else if (value instanceof Set) {
            Set set = (Set) value;
            Set<String> newSet = new HashSet<>();
            for (Object object : set) {
                newSet.add((String)object);
            }
            editor.putStringSet(key, newSet);
        } else {
            throw new IllegalArgumentException("Unsupported value type");
        }

        editor.apply();
    }

    public Object getValue(String key, Object defaultValue) {
        if (defaultValue instanceof String) {
            return SETTING_PREF.getString(key, (String) defaultValue);
        } else if (defaultValue instanceof Boolean) {
            return SETTING_PREF.getBoolean(key, (Boolean) defaultValue);
        } else if (defaultValue instanceof Float) {
            return SETTING_PREF.getFloat(key, (Float) defaultValue);
        } else if (defaultValue instanceof Integer) {
            return SETTING_PREF.getInt(key, (Integer) defaultValue);
        } else if (defaultValue instanceof Long) {
            return SETTING_PREF.getLong(key, (Long) defaultValue);
        } else if (defaultValue instanceof Set) {
            return SETTING_PREF.getStringSet(key, (Set<String>) defaultValue);
        } else {
            return null;
        }
    }
}
